package org.javaboy.web.controller.ai_interview;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.javaboy.common.annotation.Anonymous;
import org.javaboy.common.config.AiInterviewConfig;
import org.javaboy.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/file")
public class FileController {

    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");

    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file, HttpServletRequest req) {
        String format = sdf.format(new Date());
        String path = AiInterviewConfig.getProfile() + format;
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = System.currentTimeMillis() + oldName.substring(oldName.lastIndexOf("."));
        try {
            file.transferTo(new File(folder, newName));
            // http://lcocalhost:8080/file/view/2024/09/01/1657480239488.jpg
            String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/file/view" + format + newName;
            return AjaxResult.success(url);
        } catch (IOException e) {
            return AjaxResult.error("上传失败");
        }
    }

    @GetMapping("/view/{year}/{month}/{day}/{name}")
    public void viewImage(HttpServletResponse resp, @PathVariable String year, @PathVariable String month, @PathVariable String day, @PathVariable String name) throws IOException {
        String path = AiInterviewConfig.getProfile() + "/" + year + "/" + month + "/" + day;
        File file = new File(path, name);
        if (!file.exists()) {
            resp.setStatus(404);
            return;
        }
        byte[] bytes = new byte[(int) file.length()];
        try (FileInputStream fis = new FileInputStream(file)) {
            fis.read(bytes);
            resp.setContentLength((int) file.length());
            resp.setContentType("image/jpeg");
            resp.getOutputStream().write(bytes);
        }
    }
}
